package com.bdqn.newdream.service;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.ibatis.annotations.Param;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.web.multipart.MultipartFile;

import com.bdqn.newdream.Impl.AcceptMapper;
import com.bdqn.newdream.Impl.CollectMapper;
import com.bdqn.newdream.Impl.CommentMapper;
import com.bdqn.newdream.Impl.DreamuserMapper;
import com.bdqn.newdream.Impl.IndividuationMapper;
import com.bdqn.newdream.Impl.LikeMapper;
import com.bdqn.newdream.Impl.MessageMapper;
import com.bdqn.newdream.Impl.ProblemMapper;
import com.bdqn.newdream.javabean.AProblem;
import com.bdqn.newdream.javabean.DreamingUser;
import com.bdqn.newdream.javabean.Imgjson;
import com.bdqn.newdream.javabean.Problemlist;
import com.bdqn.newdream.javabean.ReComment;
import com.bdqn.newdream.pojo.Accept;
import com.bdqn.newdream.pojo.Collect;
import com.bdqn.newdream.pojo.Comment;
import com.bdqn.newdream.pojo.Dreamuser;
import com.bdqn.newdream.pojo.Individuation;
import com.bdqn.newdream.pojo.Like;
import com.bdqn.newdream.pojo.Message;
import com.bdqn.newdream.pojo.Problem;
import com.bdqn.newdream.service.Impl.DreamuserServiceImpl;

@Service("dreamuserService")
public class DreamuserService implements DreamuserServiceImpl {
	@Resource(name="messageMapper")
	private MessageMapper message;
	@Resource(name="likeMapper")
	private LikeMapper like;
	
	@Resource(name="acceptMapper")
	private AcceptMapper accept;
	@Resource(name="collectMapper")
	private CollectMapper collect;
	@Resource(name="individuationMapper")
	private IndividuationMapper individuationMapper;
	
	@Resource(name="commentMapper")
	private CommentMapper comment;
	/*
	 * 问题表的dao接口
	 */
	@Resource(name="problemMapper")
	private ProblemMapper problem;
	/*
	 * 用户表的dao接口
	 */
	@Resource(name="dreamuserMapper")
	private DreamuserMapper dreamuser;
	
	/*
	 * (Service层登录验证)
	 * @see com.bdqn.newdream.service.Impl.DreamuserServiceImpl#loginuser(java.lang.String, java.lang.String)
	 */
	@Override
	public DreamingUser loginuser(String name, String pwd) {
		if(name==null||pwd==null||name.length()<=0||pwd.length()<=0)
			return null;
		DreamingUser user=dreamuser.gologin(name, pwd);
		if(user!=null&&user.getMessage()!=null)
			user.setId(user.getMessage().getUid());
		return user!=null&&user.getId()!=null?user:null;//判断user是否为空，判断user的id是否为空，为空返回null
	}
	/*
	 * 统计问题总页
	 */
	public Integer countProblem(){
		int count=problem.countProblemlist(1);
		if(count%16==0){
			count=count/16;
		}else{
			count=(int)(count/16);
			count+=1;
		}
		return count;
	}
	/*
	 * (测试)
	 * @see com.bdqn.newdream.service.Impl.DreamuserServiceImpl#getdreamuser()
	 */
	@Override
	public List<Dreamuser> getdreamuser() {
		return dreamuser.selectByExample(null);
	}
	/*
	 * 
	 * (Service查询main页面需要问题列表返回List集合)
	 * @see com.bdqn.newdream.service.Impl.DreamuserServiceImpl#getProblemlist(java.lang.Integer)
	 */
	@Override
	public List<Problemlist> getProblemlist(Integer id,Integer uid,Integer page){
		int num =(page-1)*16;//处理分页
		return problem.selectProblemlist(id,uid,num);
	}
	
	/*
	 * (Service保存图片，富文本域使用)
	 * @see com.bdqn.newdream.service.Impl.DreamuserServiceImpl#getImgjson(org.springframework.web.multipart.MultipartFile)
	 */
	@Override
	public Imgjson saveImgjson(MultipartFile file,HttpServletRequest request) {
		Imgjson imgjson=new Imgjson();
		if(file!=null&&file.getOriginalFilename()!=null&&file.getOriginalFilename().length()>0){
			String origName=file.getOriginalFilename();//得到文件名
			String extendsName=origName.substring(origName.lastIndexOf("."));//得到文件后缀BMP、JPG、JPEG、PNG、GIF。 BMP
			if(extendsName.equals(".bmp")||extendsName.equals(".jpg")||extendsName.equals(".jpeg")||extendsName.equals(".png")||extendsName.equals(".gif")){
				//SimpleDateFormat df = new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒");//设置日期格式  
				String randanddate=UUID.randomUUID().toString(); // new Date()为获取当前系统时间  
				String filename="C:\\dreamimg\\"+randanddate+extendsName;
				File uploadFile=new File(filename);
				try {
					file.transferTo(uploadFile);
					imgjson.setErrno(0);//0表示没有错误
					String [] Data={request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()+"/imgfile/"+randanddate+extendsName};
					imgjson.setData(Data);
					return imgjson;
				} catch (IllegalStateException | IOException e) {
					imgjson.setErrno(1);//1文件上传异常
					return imgjson;
				}
			}else{
				imgjson.setErrno(2);//2用户上传的文件格式不正确
			}
		}else{
			imgjson.setErrno(3);//3用户没有上传文件
		}
		return imgjson;
	}
	
	
	/*
	 * (未登录的分页)
	 * @see com.bdqn.newdream.service.Impl.DreamuserServiceImpl#problemlist(java.lang.Integer, java.lang.Integer)
	 */
	@Override
	public List<Problemlist> problemlist(Integer id,Integer page) {
		int num =(page-1)*16;//处理分页
		return problem.Problemlist(id,num);
	}
	/*
	 * (保存用户发表的问题)
	 * @see com.bdqn.newdream.service.Impl.DreamuserServiceImpl#saveProblem()
	 */
	@Override
	public Integer saveProblem(Problem aproblem){
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		aproblem.setNum(0);
		aproblem.setTime(df.format(new Date()));
		aproblem.setState(1);
		return problem.insertSelective(aproblem);
	}
	public void loadmain(HttpSession session,Model model,Integer page){
		DreamingUser temp=(DreamingUser)session.getAttribute("user");
		model.addAttribute("page", countProblem());
		model.addAttribute("thispage",page);
		if(temp!=null)
			model.addAttribute("problem",getProblemlist(1,temp.getId(),page));
		else
			model.addAttribute("problem",problemlist(1,page));
	}
	/*
	 * (查询问题内容)
	 * @see com.bdqn.newdream.service.Impl.DreamuserServiceImpl#selectAProblem(java.lang.Integer, java.lang.Integer)
	 */
	public AProblem selectAProblem(Integer id,Integer uid){
		AProblem temp=problem.aProblem(1,id, uid);
		if(temp!=null){
			temp.setUid(temp.getMessage().getUid());
			temp.setCount(temp.getComment().size());
			for(int i=0;i<temp.getComment().size();i++){
				temp.getComment().get(i).setRelikeid(like.selectlike(temp.getComment().get(i).getId(), uid));
			}
		}
		addnum(id);
		return temp;
	}
	/*
	 * (查询问题内容)
	 * @see com.bdqn.newdream.service.Impl.DreamuserServiceImpl#selectAProblem(java.lang.Integer)
	 */
	public AProblem selectAProblem(Integer id){
		AProblem temp=problem.reProblem(1,id);
		if(temp!=null){
			temp.setUid(temp.getMessage().getUid());
			temp.setCount(temp.getComment().size());
		}
		addnum(id);
		return temp;
	}
	public Comment doem(){
		return comment.temp(7);
		
	}
	
	public Integer deleteByindividuation(Integer id){
		return individuationMapper.deleteByPrimaryKey(id);
	}
	
	public Integer insertindividuation(Integer pid,Integer uid){
		Individuation record=new Individuation();
		record.setPid(pid);
		record.setUid(uid);
		return individuationMapper.insert(record);
	}
	public Integer delectAProbleam(Integer id){
		return problem.delectAProbleam(id);
	}
	public Integer selectsaveiid(Integer uid,Integer pid){
		return individuationMapper.selectindividutaionid(uid, pid);
	}
	public Integer selectsavecollect(Integer uid,Integer pid){
		Collect record=new Collect();
		record.setUid(uid);
		record.setPid(pid);
		return collect.insert(record);
	}
	public Integer selectcid(Integer uid,Integer pid){
		return collect.selectcid(uid, pid);
	}
	
	public Integer dropcollect(Integer id){
		return collect.deleteByPrimaryKey(id);
	}
	public Integer dropcomment(Integer id){
		return comment.deleteByPrimaryKey(id);
	}
	public Integer savecomment(Integer uid,Integer pid,String text,Integer state){
		Comment temp=new Comment();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		temp.setTime(df.format(new Date()));
		temp.setPid(pid);
		temp.setText(text);
		temp.setState(state);
		temp.setUid(uid);
		return comment.insert(temp);
	}
	public Integer saveaccept(Integer pid,Integer cid){
		Accept temp=new Accept();
		temp.setCid(cid);
		temp.setPid(pid);
		return accept.insert(temp);
	}
	
	public Integer selectaccept(Integer pid,Integer cid){
		return accept.saveAccept(pid, cid);
	}
	
	
	public int saveLike(Integer cid,Integer uid){
		Like temp=new Like();
		temp.setCid(cid);
		temp.setUid(uid);
		Integer num;
		if(like.insert(temp)>0){
			return 1;
		}else{
			return 3;
		}
	}
	public Integer selectlikeid(Integer cid,Integer uid){
		return like.selectlike(cid, uid);
	}
	
	public Integer dorplike(Integer cid,Integer uid){
		like.droplike(cid, uid);
		return 1;
	}
	
	public Integer addnum(Integer id){
		return problem.selectaddnum(id);
	}
	
	public List<Problem> Firstnum(Integer id){
		return problem.firstnum(id);
	}
	
	public List<Problemlist> Firstcount(Integer id){
		return problem.firstcount(id);
	}
	
	public Integer countlikep(String title){
		Integer count=problem.countlike(1,title);
		if(count%16==0){
			count=count/16;
		}else{
			count=(int)(count/16);
			count+=1;
		}
		return count;
	}
	 
	public List<Problemlist> likeprobleam(String title,Integer page){
		return problem.likeprobleam(1,title,(page-1)*16);
	}
	public String rand(){
		Random rand=new Random();
		String key=rand.nextInt(9)+""+rand.nextInt(9)+""+rand.nextInt(9)+""+rand.nextInt(9)+""+rand.nextInt(9)+""+rand.nextInt(9)+"";
		return key;
	}
	public String randuser(){
		Random rand=new Random();
		String key=rand.nextInt(9)+""+rand.nextInt(9)+""+rand.nextInt(9)+""+rand.nextInt(9)+""+rand.nextInt(9)+""+rand.nextInt(9)+rand.nextInt(9)+rand.nextInt(9)+"";
		return key;
	}
	public void updatekey(String username){
		dreamuser.updatekey(rand(), username);
	}
	public String sendkey(String username){
		dreamuser.updatekey(rand(), username);
		Dreamuser user=dreamuser.sendkey(username);
		if(user!=null&&user.getNamekey()!=null){
			if(Email.email(user.getEmail(), user.getNamekey())){
				return "验证码已发送!";
			}else{
				return "系统异常!";
			}
		}else{
			return "用户名不存在！";
		}
	}
	
	public Integer updatepass(String username,String pass,String key){
		return dreamuser.updatepass(pass, username, key);
	}
	
	public boolean selectemail(String email){
		
		if(dreamuser.selectemail(email)!=null){
			return true;
		}else{
			return false;
		}
	}
	public String newdream(Dreamuser user,Message message1,Model model,HttpServletRequest request){
		user.setState(0);//设置状态
		user.setNamekey(rand());//设置验证码
		user.setKeyname(UUID.randomUUID().toString()+UUID.randomUUID().toString());//设置激活码
		String http=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+"/dreaming/activate";
		message1.setImg("file/res/images/avatar/"+new Random().nextInt(9)+".jpg");//设置头像地址
		message1.setName("保密");//设置真实姓名
		message1.setAge(0);//设置年龄
		message1.setSex("保密");//设置性别
		String username=randuser();
	 	for(;dreamuser.selectusername(username)!=null;){
			username=randuser();
		}
		if(dreamuser.selectemail(user.getEmail())==null){
			if(Email.newemail(user.getEmail(),user.getKeyname() ,http,message1.getNickname(),"新梦想提示您<br/>您登录新梦想社区的唯一用户名为:   "+username+"   请牢记！这是您唯一能登录的用户名!")){
				user.setUsername(username);//设置用户名
				//保存用户
				Integer temp=dreamuser.newdream(user);
				message1.setUid(user.getId());//设置用户id
				message.insertnew(message1.getUid(),message1.getName(), message1.getAge(), message1.getImg(), message1.getSex(),message1.getNickname());//插入用户信息
				model.addAttribute("tishi","注册成功！你的登录的用户名为:"+username+"。激活邮件已发送至您的邮箱，请尽快激活用户!");
				return "newdream";
			}else{
				model.addAttribute("tishi2", "邮箱不正确");
				model.addAttribute("username", user.getUsername());
				model.addAttribute("pass",user.getPwd());
				return "login";
			}
		}else{
			model.addAttribute("tishi2","邮箱已被注册!");
			model.addAttribute("username", user.getUsername());
			model.addAttribute("pass",user.getPwd());
			return "login";
		}
		
	}
	public Integer activate(String key){
		return dreamuser.activate(key);
	}
	
	public DreamingUser gomessage(Integer id){
		return dreamuser.gomessage(id);
	}
	public Integer updateByPrimaryKey(Message message1){
		return message.updateByPrimaryKeySelective(message1);
	}
	
	public String saveImg(MultipartFile file,HttpServletRequest request) {
		if(file!=null&&file.getOriginalFilename()!=null&&file.getOriginalFilename().length()>0){
			String origName=file.getOriginalFilename();//得到文件名
			String extendsName=origName.substring(origName.lastIndexOf("."));//得到文件后缀BMP、JPG、JPEG、PNG、GIF。 BMP
			if(extendsName.equals(".bmp")||extendsName.equals(".jpg")||extendsName.equals(".jpeg")||extendsName.equals(".png")||extendsName.equals(".gif")){
				//SimpleDateFormat df = new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒");//设置日期格式  
				String randanddate=UUID.randomUUID().toString(); // new Date()为获取当前系统时间  
				String filename="C:\\userimg\\"+randanddate+extendsName;
				File uploadFile=new File(filename);
				try {
					file.transferTo(uploadFile);
					String  Data=request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()+"/userimg/"+randanddate+extendsName;
					return Data;
				} catch (IllegalStateException | IOException e) {
					return null;
				}
			}else{
				return null;//2用户上传的文件格式不正确
			}
		}else{
			return null;//3用户没有上传文件
		}
	}
	
	public Dreamuser selectByPrimaryKey(Integer id){
		return dreamuser.selectByPrimaryKey(id);
	}
	public boolean senduser(String title,String text,String email){
		return Email.email2(title, email, text);
	}
}
